package com.cskaoyan.service;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.params.AdminInsertBO;
import com.cskaoyan.bean.params.AdminListBO;
import com.cskaoyan.bean.params.BaseParam;
import com.cskaoyan.mapper.AdminMapper;
import com.cskaoyan.mapper.PermissionMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sun.xml.internal.bind.v2.model.core.ID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.System;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;

/**
 * @USER: cuiweiguo#
 * @DATE: 2022/5/5
 * @TIME: 19:11
 * @PROJECT_NAME: mallproject2
 */
@Service
public class AuthServiceImpl implements AuthService {
    @Autowired
    AdminMapper adminMapper;

    @Autowired
    PermissionMapper permissionMapper;

    @Override
    public int queryAdminByUsernameAndPassword(String username, String password) {
        //查询
        AdminExample adminExample = new AdminExample();

        AdminExample.Criteria criteria = adminExample.createCriteria();//sql语句的拼接 ${}

        if (username != null && !"".equals(username)) {
            criteria.andUsernameEqualTo(username);
        }
        if (password != null && !"".equals(password)) {
            criteria.andPasswordEqualTo(password);
        }
        long count = adminMapper.countByExample(adminExample);
        if (count == 1) {
            return 200;
        } else {
            return 0;
        }

    }

    @Override
    public AdminListBean queryAdminList(BaseParam baseParam, String username) {
        //查询总共所有的数量
        Integer page = baseParam.getPage();//页码
        Integer limit = baseParam.getLimit();//数据量
        String sort = baseParam.getSort();//排序列
        String order = baseParam.getOrder();//desc\asc
        //分页插件 PageHelper，辅助我们做分页以及分页信息的获得
        PageHelper.startPage(page, limit);
        //执行查询过程中拼接分页信息
        //  username="%"+username+"%";
        List<AdminListBO> list = adminMapper.select(sort, order, username);

        //total、pages、list
        //通过PageHelper帮我们来获得一些和分页相关的信息PageInfo
        //使用其有参构造方法 → 形参写来源于数据库的list
        PageInfo<AdminListBO> pageInfo = new PageInfo<>(list);
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();
        return AdminListBean.data(total, pages, limit, page, list);
    }

    @Override
    public int deleteAdmin(AdminListBO adminListBO) {

        AdminExample adminExample = new AdminExample();
        AdminExample.Criteria criteria = adminExample.createCriteria();//sql语句的拼接 ${}

        criteria.andIdEqualTo(adminListBO.getId());

        if (adminListBO.getUsername() != null && !"".equals(adminListBO.getUsername())) {
            criteria.andUsernameEqualTo(adminListBO.getUsername());
        }
        if (adminListBO.getAvatar() != null && !"".equals(adminListBO.getAvatar())) {
            criteria.andAvatarEqualTo(adminListBO.getAvatar());
        }
        /*if (adminListBO.getRoleIds() != null && !"".equals(adminListBO.getRoleIds())) {
            criteria.andRoleIdsEqualTo(adminListBO.getRoleIds());
        }*/

        int affectedRows = adminMapper.deleteByExample(adminExample);
        if (affectedRows == 1) {
            return 200;
        } else {
            return 0;
        }
    }

    @Override
    public AdminCreatePO insertAdmin(AdminInsertBO adminInsertBO) {
        Date date = new Date(System.currentTimeMillis());
        //插入数据
        //TODO：先不考录密码加密
        Admin admin = new Admin(null, adminInsertBO.getUsername(), adminInsertBO.getPassword(), null, null, adminInsertBO.getAvatar(),
                date, date, null, adminInsertBO.getRoleIds());
        int i = adminMapper.insertSelectiveUsingGeneralKey(admin);
        //
        AdminCreatePO adminCreatePO = new AdminCreatePO(
                admin.getId(), admin.getUsername(), admin.getPassword(), admin.getAvatar(), admin.getAddTime(), admin.getUpdateTime(),
                admin.getRoleIds());
        if (i == 1) {
            return adminCreatePO;
        }
        return null;
    }

    @Override
    public AdminUpdatePO updateAdmin(AdminUpdateBO adminUpdateBO) {
        Admin admin = new Admin(adminUpdateBO.getId(), adminUpdateBO.getUsername(), adminUpdateBO.getPassword(), null, null, adminUpdateBO.getAvatar(),
                null, new Date(System.currentTimeMillis()), null, adminUpdateBO.getRoleIds());
        int affectedRows = adminMapper.updateByPrimaryKeySelective(admin);
        //TODO：未写，这里应该先做的是查询
        return new AdminUpdatePO(admin.getId(), admin.getUsername(), admin.getAvatar(), admin.getUpdateTime(), admin.getRoleIds());
    }

    @Override
    public int queryAdminIdByUsernameAndPassword(String username, String password) {
        //查询

        int id = adminMapper.selectIdByNameAndPassword(username, password);
        return id;
    }

    @Override
    public List<String> getOptionsByUserId(Integer userId) {
        //通过用户Id获得角色id---roleId
        Integer[] roleIds = adminMapper.getRolesByUserId(userId);
        List<String> list = new ArrayList<>();
        LinkedHashSet<String> set = new LinkedHashSet<>();

        for (Integer roleId : roleIds) {
            PermissionExample permissionExample = new PermissionExample();
            permissionExample.createCriteria()
                    .andRoleIdEqualTo(roleId)
                    .andDeletedEqualTo(false);
            List<Permission> permissions = permissionMapper.selectByExample(permissionExample);
            for (Permission permission : permissions) {
                String permissionStr = permission.getPermission();
                set.add(permissionStr);
            }
        }
        list.addAll(set);

        return list;
    }

    /**
     * @Description:
     * @Author: cuiweiguo#
     * @Date: 2022/5/10 14:18
     * @Param: [userId]:
     * @return: com.cskaoyan.bean.AdminInfoBean:
     **/
    @Override
    public AdminInfoBean queryAdminInfoById(Integer userId) {

        AdminInfoBean adminInfoBean = adminMapper.queryAdminInfoById(userId);

        return adminInfoBean;
    }

    @Override
    public String queryUsernameById(Integer userId) {

        String username = adminMapper.queryUsernameById(userId);

        return username;
    }
    /**
     * @Description:
     * @Author: cuiweiguo#
     * @Date: 2022/5/10 22:23
     * @Param: [userId, ip]:
     * @return: void:
     **/
    @Override
    public void updateIpByUserId(Integer userId, String ip) {
        adminMapper.updateIpByUserId(userId,ip);

    }
}
